package cn.fl.capital.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapAdvFundQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.service.ICapAdvFundService;
import cn.fl.capital.vo.CapAdvFundVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 垫款资金流水表 控制层
 */
@Controller
@RequestMapping("/capital/capAdvFund")
public class CapAdvFundController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CapAdvFundController.class);

    /**
     * CapAdvFund 服务层BEAN
     */
    @Autowired
    private ICapAdvFundService capAdvFundService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService ;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载CapAdvFund列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvFund/capAdvFundList");
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载CapAdvFund Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvFund/capAdvFundModify");
        this.prepare(request,mav);
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载CapAdvFund Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvFund/capAdvFundModify");
        this.prepare(request,mav);

        String id = request.getParameter("id");
        CapAdvFundVO capAdvFundVO = this.capAdvFundService.selectById(Long.valueOf(id));
        mav.addObject("capAdvFundVO", capAdvFundVO);
        return mav;
    }

    //加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request, ModelAndView mav) {
        //规则状态 （"0": 未开启,"1":已开启）
        List<KeyValueVO> advStatusKvList = this.sysDictionaryApiService.getKvList("", CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //垫款日期类型（CAP0033 1：工作日 2：自然日(暂不考虑)）
        List<KeyValueVO> advDtKvList = this.sysDictionaryApiService.getKvList("",CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //垫款周期CAP0034 （1~5 ： 周一~周五）
        List<KeyValueVO> advPeriodKVList = this.sysDictionaryApiService.getKvList("",CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //CAP0029 垫款日期
        List<KeyValueVO> advTmKvList = this.sysDictionaryApiService.getKvList("",CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //垫款逾期天数CAP0030
        List<KeyValueVO> advOverDueDaysKvList = this.sysDictionaryApiService.getKvList("",CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //垫款逾期期数CAP0031
        List<KeyValueVO> advOverDuePayPdKvList = this.sysDictionaryApiService.getKvList("",CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //垫款方式CAP0032
        List<KeyValueVO> advWayKvList = this.sysDictionaryApiService.getKvList("",CapitalConstant.SYSCD,CapitalConstant.SYSORG);

        if(CollectionUtils.isNotEmpty(advStatusKvList)){
            mav.addObject("advStatusKvList", JSON.toJSONString(advStatusKvList));
        }

        if(CollectionUtils.isNotEmpty(advDtKvList)){
            mav.addObject("advDtKvList", JSON.toJSONString(advDtKvList));
        }

        if(CollectionUtils.isNotEmpty(advPeriodKVList)){
            mav.addObject("advPeriodKVList", JSON.toJSONString(advPeriodKVList));
        }

        if(CollectionUtils.isNotEmpty(advTmKvList)){
            mav.addObject("advTmKvList", JSON.toJSONString(advTmKvList));
        }

        if(CollectionUtils.isNotEmpty(advOverDueDaysKvList)){
            mav.addObject("advOverDueDaysKvList", JSON.toJSONString(advOverDueDaysKvList));
        }

        if(CollectionUtils.isNotEmpty(advOverDuePayPdKvList)){
            mav.addObject("advOverDuePayPdKvList", JSON.toJSONString(advOverDuePayPdKvList));
        }

        if(CollectionUtils.isNotEmpty(advWayKvList)){
            mav.addObject("advWayKvList", JSON.toJSONString(advWayKvList));
        }
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initCapAdvFundList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CapAdvFundQueryCondition qc = new CapAdvFundQueryCondition();
        //TODO 设置查询条件？
        String searchName = request.getParameter("searchName");
        if (StringUtils.isNotEmpty(searchName)) {

        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initCapAdvFundList", "初始化CapAdvFund列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capAdvFundService.searchListPage(page);
        List<CapAdvFundVO> list = (List<CapAdvFundVO>) pager.getResultList();
        ListPageVO<CapAdvFundVO> listPage = new ListPageVO<CapAdvFundVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeCapAdvFundByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapAdvFundByIds", "删除CapAdvFund数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            boolean success = this.capAdvFundService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeCapAdvFundByIds", "删除CapAdvFund数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeCapAdvFundByIds", "删除CapAdvFund数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeCapAdvFundByIds", "删除CapAdvFund数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeCapAdvFundByIds", "删除CapAdvFund数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getCapAdvFundById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getCapAdvFundById", "获取CapAdvFund数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            CapAdvFundVO vo = this.capAdvFundService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getCapAdvFundById", "获取CapAdvFund数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getCapAdvFundById", "获取CapAdvFund数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getCapAdvFundById", "获取CapAdvFund数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getCapAdvFundById", "获取CapAdvFund数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addCapAdvFund(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        CapAdvFundVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForCapAdvFund(request);//获取参数
            Long id = this.capAdvFundService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "addCapAdvFund", "新增CapAdvFund数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addCapAdvFund", "新增CapAdvFund数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addCapAdvFund", "新增CapAdvFund数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyCapAdvFund(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        CapAdvFundVO entity = null;
        try {
            entity = this.getRequestParamForCapAdvFund(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyCapAdvFund", "修改CapAdvFund信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
                return result;
            }

            boolean success = this.capAdvFundService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyCapAdvFund", "修改CapAdvFund数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyCapAdvFund", "修改CapAdvFund数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyCapAdvFund", "修改CapAdvFund数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyCapAdvFund", "修改CapAdvFund数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private CapAdvFundVO getRequestParamForCapAdvFund(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String code = request.getParameter("code");//资金编号（x） 垫款（DK+ID）冲销（HB+ID）
        String batchId = request.getParameter("batchId");//批次号（流水号）
        String cstId = request.getParameter("cstId");//客户ID
        String cstNm = request.getParameter("cstNm");//客户名称
        String payAmt = request.getParameter("payAmt");//金额
        String payBkId = request.getParameter("payBkId");//付款银行账户ID(SYS_BK_ACC_INFO表ID、BANK_ACC_INFO表ID)
        String payAccNo = request.getParameter("payAccNo");//付款账号
        String payAccNm = request.getParameter("payAccNm");//付款账户
        String payBkNm = request.getParameter("payBkNm");//付款开户银行
        String payBkNo = request.getParameter("payBkNo");//付款银行开户行号
        String dueBkId = request.getParameter("dueBkId");//收款银行账户ID(SYS_BK_ACC_INFO表ID、BANK_ACC_INFO表ID)
        String dueAccNo = request.getParameter("dueAccNo");//收款账户
        String dueAccNm = request.getParameter("dueAccNm");//收款户名
        String dueBkNm = request.getParameter("dueBkNm");//收款开户银行
        String dueBkNo = request.getParameter("dueBkNo");//收款银行开户行号
        String capAttrCd = request.getParameter("capAttrCd");//资金属性(CAP0027 ): 1.租赁人还款资金 2.垫款资金 3.回拨资金
        String advRetTime = request.getParameter("advRetTime");//实际垫款/回拨时间
        String fundStsCd = request.getParameter("fundStsCd");//资金垫款/回拨状态CAP0036： 1.未发送2.已发送 3.付款成功 4.付款失败5.已垫款6.已核销7.已作废
        String relFundId = request.getParameter("relFundId");//关联资金ID
        String advRuleId = request.getParameter("advRuleId");//垫款规则ID
        String fundTypCd = request.getParameter("fundTypCd");//资金生成方式CAP0037：1.自动 2.手动
        String fundRem = request.getParameter("fundRem");//备注
        String version = request.getParameter("version");//版本

        //验证参数并赋值
        CapAdvFundVO entity = new CapAdvFundVO();
        //entity.setCode(code);//资金编号（x） 垫款（DK+ID）冲销（HB+ID）
        //entity.setBatchId(batchId);//批次号（流水号）
        //entity.setCstId(cstId);//客户ID
        //entity.setCstNm(cstNm);//客户名称
        //entity.setPayAmt(payAmt);//金额
        //entity.setPayBkId(payBkId);//付款银行账户ID(SYS_BK_ACC_INFO表ID、BANK_ACC_INFO表ID)
        //entity.setPayAccNo(payAccNo);//付款账号
        //entity.setPayAccNm(payAccNm);//付款账户
        //entity.setPayBkNm(payBkNm);//付款开户银行
        //entity.setPayBkNo(payBkNo);//付款银行开户行号
        //entity.setDueBkId(dueBkId);//收款银行账户ID(SYS_BK_ACC_INFO表ID、BANK_ACC_INFO表ID)
        //entity.setDueAccNo(dueAccNo);//收款账户
        //entity.setDueAccNm(dueAccNm);//收款户名
        //entity.setDueBkNm(dueBkNm);//收款开户银行
        //entity.setDueBkNo(dueBkNo);//收款银行开户行号
        //entity.setCapAttrCd(capAttrCd);//资金属性(CAP0027 ): 1.租赁人还款资金 2.垫款资金 3.回拨资金
        //entity.setAdvRetTime(advRetTime);//实际垫款/回拨时间
        //entity.setFundStsCd(fundStsCd);//资金垫款/回拨状态CAP0036： 1.未发送2.已发送 3.付款成功 4.付款失败5.已垫款6.已核销7.已作废
        //entity.setRelFundId(relFundId);//关联资金ID
        //entity.setAdvRuleId(advRuleId);//垫款规则ID
        //entity.setFundTypCd(fundTypCd);//资金生成方式CAP0037：1.自动 2.手动
        //entity.setFundRem(fundRem);//备注
        //entity.setVersion(version);//版本

//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            //entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
        }

        return entity;
    }
}

